package fr.blogger.web.bean.securite;

import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import fr.blogger.web.outils.UtilsJsf;

@Named
public class AuthentificationBean {

	private static final String SPRING_SECURITY_LOGIN = "/j_spring_security_check";

	private static final String SPRING_SECURITY_LOGOUT = "/j_spring_security_logout";

	private static final String SPRING_SECURITY_SWITCH_USER = "/j_spring_security_switch_user";

	private static final String SPRING_SECURITY_EXIT_USER = "/j_spring_security_exit_user";

	private String login;

	private String password;

	public AuthentificationBean() {
	}

	@PostConstruct
	private void initialisation() {
		String messageServlet = (String) FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("javax.servlet.error.message");
		if (messageServlet != null) {
			UtilsJsf.ajoutMessageError(messageServlet);
		}
	}

	private RequestDispatcher getDispatcher(ExternalContext pContext, String pSpringAction) {
		return ((ServletRequest) pContext.getRequest()).getRequestDispatcher(pSpringAction);
	}

	public String doLogin() throws IOException, ServletException {
		this.doForward(SPRING_SECURITY_LOGIN);
		return null;
	}

	public String doLogOut() throws ServletException, IOException {
		this.doForward(SPRING_SECURITY_LOGOUT);
		return null;
	}

	private void doForward(String url) throws ServletException, IOException {
		ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
		RequestDispatcher dispatcher = this.getDispatcher(context, url);
		dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());
		FacesContext.getCurrentInstance().responseComplete();
	}

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
